package com.alinesno.cloud.common.core.dubbo.advice;

import org.apache.dubbo.rpc.RpcContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.alinesno.cloud.common.core.dubbo.BaseFilter;
import com.alinesno.cloud.common.facade.wrapper.RestWrapper;

/**
 * Dubbo 请求参数修改及配置
 * @author WeiXiaoJin
 * @since 2019年4月8日 下午8:30:43
 */
@Order(1)
@Aspect
@Component
public class DubboTenantProviderAdvice extends BaseFilter {
	
	private static final Logger log = LoggerFactory.getLogger(DubboTenantProviderAdvice.class);
   
    
    @Pointcut("@annotation(com.alinesno.cloud.common.core.annotations.TenantMethod)")  
    public void pointcut(){
    }
 
    //统计请求的处理时间
    ThreadLocal<Long> startTime = new ThreadLocal<>();
   
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) {
        Object result = null;
        RpcContext ctx = RpcContext.getContext() ;  
        String applicationId = ctx.getAttachment(APPLICATION_ID);
		String operatorId = ctx.getAttachment(OPERATOR_ID);
		
		log.debug("application id:{} , operator id:{}" , applicationId , operatorId);
		
        try {
        	// 修改Dubbo参数_start
        	Object[] args = point.getArgs();
        	
        	for(int i = 0 ; i < args.length ; i ++) {
				Object a = args[i] ; 
				if(a instanceof RestWrapper) {  // 参数权限
					RestWrapper r = (RestWrapper) a ; 
					if(!r.isRemoveApplication()) {
						r.eq(APPLICATION_ID, applicationId) ; 
					}
					r.eq(OPERATOR_ID, operatorId) ; 
					
					args[i] = r ; // 重新赋值 
				}
			}
        	// 修改Dubbo参数_end 
        	
        	log.debug("change args:{}" , JSONObject.toJSON(args));
        	
            result = point.proceed(args); // 执行方法
        } catch (Throwable e) {
        	log.error("Dubbo调用错误:{}" , e);
        }
        return result;
    }
 
}


